import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:stars_moon/utils/config.dart';

class AuthStore extends ChangeNotifier {
  String? _phone;
  String? _username;
  bool _loggedIn = false;
  final String _baseUrl = CommonConfig.baseUrl;
  String? get phone => _phone;
  String? get username => _username;
  bool get loggedIn => _loggedIn;
  Map<String, dynamic>? lastVersionData;

  Future<void> load() async {
    final prefs = await SharedPreferences.getInstance();
    _phone = prefs.getString('auth.phone');
    _username = prefs.getString('auth.username');
    _loggedIn = prefs.getBool('auth.loggedIn') ?? false;
    notifyListeners();
  }

  Future<void> registerRemote({required String username, required String password, required String phone}) async {
    final uri = Uri.parse('$_baseUrl/api/v1/auth/register');
    final resp = await http
        .post(
          uri,
          headers: {'Content-Type': 'application/json'},
          body: jsonEncode({'username': username, 'password': password, 'phone': phone}),
        )
        .timeout(const Duration(seconds: 10));
    print('注册url: $uri, username: $username, password: $password, phone: $phone');
    print('注册结果: ${resp.statusCode}');
    if (resp.statusCode != 200) {
      throw Exception('注册失败: HTTP ${resp.statusCode}');
    }
    final data = jsonDecode(resp.body) as Map<String, dynamic>;
    if ((data['code'] ?? 500) != 200) {
      throw Exception(data['message'] ?? '注册失败');
    }
    final dd = (data['data'] ?? {}) as Map<String, dynamic>;
    final savedUsername = dd['username']?.toString() ?? username;
    final savedPhone = dd['phone']?.toString() ?? phone;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('auth.phone', savedPhone);
    await prefs.setString('auth.username', savedUsername);
    await prefs.setBool('auth.loggedIn', true);
    _phone = savedPhone;
    _username = savedUsername;
    _loggedIn = true;
    notifyListeners();
  }

  Future<void> loginRemote({required String phone, required String password, required String deviceType}) async {
    final uri = Uri.parse('$_baseUrl/api/v1/auth/login');
    final resp = await http
        .post(
          uri,
          headers: {'Content-Type': 'application/json'},
          body: jsonEncode({'phone': phone, 'password': password, 'device_type': deviceType}),
        )
        .timeout(const Duration(seconds: 10));
    if (resp.statusCode != 200) {
      throw Exception('登录失败: HTTP ${resp.statusCode}');
    }
    final data = jsonDecode(resp.body) as Map<String, dynamic>;
    if ((data['code'] ?? 500) != 200) {
      throw Exception(data['message'] ?? '登录失败');
    }
    final dd = (data['data'] ?? {}) as Map<String, dynamic>;
    final savedUsername = dd['username']?.toString();
    final savedPhone = dd['phone']?.toString() ?? phone;
    final prefs = await SharedPreferences.getInstance();
    if (savedUsername != null) await prefs.setString('auth.username', savedUsername);
    await prefs.setString('auth.phone', savedPhone);
    await prefs.setBool('auth.loggedIn', true);
    _phone = savedPhone;
    _username = savedUsername;
    _loggedIn = true;
    notifyListeners();
  }

  Future<void> logout() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('auth.loggedIn', false);
    _loggedIn = false;
    notifyListeners();
  }

  Future<void> register({required String phone, required String username}) async {
    throw StateError('请使用新版注册页面（需填写密码）');
  }

  Future<Map<String, dynamic>> checkVersion({required String platform, required String version}) async {
    final uri = Uri.parse('$_baseUrl/api/v1/system/version/check').replace(queryParameters: {
      'platform': platform,
      'version': version,
    });
    print('版本检测url: $uri');
    final resp = await http.get(uri).timeout(const Duration(seconds: 10));
    if (resp.statusCode != 200) {
      throw Exception('版本检测失败: HTTP ${resp.statusCode}');
    }
    final data = jsonDecode(resp.body) as Map<String, dynamic>;
    print('版本检测结果: ${data['message']}');
    if ((data['code'] ?? 500) != 200) {
      throw Exception(data['message'] ?? '版本检测失败');
    }
    final dd = (data['data'] ?? {}) as Map<String, dynamic>;
    lastVersionData = dd;
    notifyListeners();
    return dd;
  }
}
